﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics;

namespace Kawanon.QtHoney
{
	internal class Dbg
	{
		public class RareException : ApplicationException
		{
		}

		public class AbortException : ApplicationException
		{
		}

		public static void Assert(bool expr)
		{
			if (!expr)
			{
				throw new AbortException();
			}
		}

		public static void Abort(string str)
		{
			StackTrace trace = new StackTrace(true);
			StackFrame[] frames = trace.GetFrames();
			if (frames.Length > 1)
			{
				StackFrame frame = frames[1];	// 直前の関数を取得
				str = String.Format("{0} {1} {2} {3} {4}",
					frame.GetFileName(), frame.GetMethod().Name,
					frame.GetFileLineNumber(), frame.GetFileColumnNumber(), str);
			}

			DialogResult res = MessageBox.Show(str, null, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error,
				MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
			if (res == DialogResult.Abort)
			{
				throw new AbortException();
			}
		}

		public class ConsoleAllocation
		{
			public ConsoleAllocation()
			{
				AllocConsole();
			}

			~ConsoleAllocation()
			{
				FreeConsole();

				//Play();
			}
		}

		[DllImport("kernel32")]
		public static extern bool AllocConsole();

		[DllImport("kernel32.dll")]
		public static extern bool FreeConsole();

		public static void Play()
		{
			System.Media.SystemSounds.Beep.Play();
		}

		public static void Br()
		{
			Echo("break");
		}

		public static void Echo(object obj)
		{
			string str;
			if (obj == null)
			{
				str = "<null>";
			}
			else
			{
				str = obj.GetType().ToString() + ": " + obj.ToString();
			}
			MessageBox.Show(str, null, MessageBoxButtons.OK, MessageBoxIcon.None,
				MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
		}

		public static void Trace(object obj)
		{
			if (Utility.IsDebugMode())
			{
				Echo(obj);
			}
		}
	}
}
